<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="ruleForm" :model="form" :rules="rules" slot="detail">
        <a-card title="商品设置" :bordered="false">
          <a-row>
            <a-col :span="24">
              <a-form-model-item label="选择商品" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="srcId">
                <div>{{form.title}}</div>
                <a-button @click="goodSelect">选择商品</a-button>
                <div class="sku-panel" v-if="form.skuList&&form.skuList.length>0" style="padding-top:0;width:100%;overflow-x:auto;">
                  <div class="sku-list">
                    <div class="sku-list-row" v-if="good_lib_type==1">
                      <div class="sku-list-col flex-2">
                        <a-popover v-model="checkSkuVisible" title="批量设置" placement="bottom" trigger="click">
                          <div class="popover-panel" slot="content">
                            <div class="popover-panel-row">
                              <a-checkbox v-model="checkedSkuAll" @change="setCheckedSkuAll">全选</a-checkbox>
                            </div>
                            <div class="popover-panel-row">
                              <a-checkbox v-model="checkedSku1" class="w-150">活动价</a-checkbox>
                              <a-input-number v-model="checkedValue1" size="small" class="pp-f-1" controls-position="right" :min="0" :precision="2"
                                :step="1" />
                            </div>
                            <div class="popover-panel-row">
                              <a-checkbox v-model="checkedSku2" class="w-150">活动库存</a-checkbox>
                              <a-input-number v-model="checkedValue2" size="small" class="pp-f-1" controls-position="right" :min="0" :step="1" />
                            </div>
                            <div class="popover-panel-row" style="padding-top:10px;text-align:right;display:block;">
                              <a-button class="mr-10" size="small" @click="checkSkuVisible = false">关闭</a-button>
                              <a-button class="mr-10" size="small" @click="setAllSkuClear">重置</a-button>
                              <a-button type="primary" size="small" @click="setAllSku">确定</a-button>
                            </div>
                          </div>
                          <a-button type="text">批量设置</a-button>
                        </a-popover>
                      </div>
                    </div>
                    <div class="sku-list-row">
                      <div class="sku-list-col flex-2 row-head">规格组</div>
                      <div class="sku-list-col row-head is-not-null" style="text-align:center;">售价</div>
                      <div class="sku-list-col row-head is-not-null" style="text-align:center;">现有库存</div>
                      <div class="sku-list-col row-head is-not-null" style="text-align:center;">活动价</div>
                      <div class="sku-list-col row-head is-not-null" style="text-align:center;">活动库存</div>

                      <div class="sku-list-col row-head" style="text-align:center;" v-if="good_lib_type==1">操作</div>
                    </div>
                    <div v-for="(item, index) in form.skuList" :key="index" class="sku-list-row">
                      <div class="sku-list-col flex-2" style="font-size:12px;">{{ item.valueNames }}</div>
                      <div class="sku-list-col" style="text-align:center;">{{ item.price }}</div>
                      <div class="sku-list-col" style="text-align:center;">{{ item.stock }}</div>

                      <div class="sku-list-col" v-if="good_lib_type==1">
                        <a-input-number v-model="item.yyPrice" size="small" class="w-80" :controls="false" :min="0" :precision="2" :step="1" />
                      </div>
                      <div class="sku-list-col" v-if="good_lib_type==1">
                        <a-input-number v-model="item.yyStock" size="small" class="w-80" :controls="false" :min="0" :step="1" />
                      </div>

                      <div class="sku-list-col" style="text-align:center;" v-if="good_lib_type==2">
                        {{ item.yyPrice }}
                      </div>
                      <div class="sku-list-col" style="text-align:center;" v-if="good_lib_type==2">
                        {{ item.yyStock }}
                      </div>

                      <div class="sku-list-col" style="text-align:center;" v-if="good_lib_type==1">
                        <a-button type="danger" v-if="item.yyStock>0" size="small" @click="item.yyStock=0">不参加</a-button>
                      </div>
                    </div>
                  </div>
                  <span>活动库存与现有库存为互相独立，假设现有库存为10件，活动库存设为5件，则您需要准备15件商品进行售卖，而并非是从10件中抽取5件进行活动。</span>
                </div>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="预售价" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="price">
                <a-input-number v-model="form.price" :disabled="good_lib_type==2" :min="0" :step="0.01" :precision="2" placeholder="请输入价格"
                  style="width: 40%" />
                <br />
                <span>此价格为商品列表中展示的价格，实际购买时以商品规格上设置的价格进行计算</span>
              </a-form-model-item>
            </a-col>

            <a-col :span="24">
              <a-form-model-item label="定金(元,限制小于商品价格)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deposit">
                <a-input-number v-model="form.deposit" :min="0" :step="0.01" :precision="2" :max="max_price" placeholder="请输入定金" style="width: 40%" />
              </a-form-model-item>
            </a-col>

            <a-col :span="24">
              <a-form-model-item label="尾款" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="deposit">
                <div>{{(form.price-form.deposit)|numToFixed2}}</div>
                <span>尾款=预售价-定金</span>
              </a-form-model-item>
            </a-col>

            <a-col :span="24">
              <a-form-model-item label="是否退定金" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="canRefund">
                <a-select v-model="form.canRefund" placeholder="请选择是否退定金" style="width: 40%">
                  <a-select-option :value="1">
                    是
                  </a-select-option>
                  <a-select-option :value="0">
                    否
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>

            <a-col :span="24">
              <a-form-model-item label="定金开始时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="startTime">
                <a-date-picker placeholder="请选择开始时间" :show-time="{ format: 'HH:mm' }" valueFormat="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm"
                  v-model="form.startTime" :disabled-date="disabledStartDate" style="width: 40%" />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="定金结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="endTime">
                <a-date-picker placeholder="请选择结束时间" :show-time="{ format: 'HH:mm' }" valueFormat="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm"
                  v-model="form.endTime" style="width: 40%" />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="尾款支付开始时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="balanceDueStartTime">
                <a-date-picker placeholder="请选择尾款开始时间" :show-time="{ format: 'HH:mm' }" valueFormat="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm"
                  v-model="form.balanceDueStartTime" style="width: 40%" />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item label="尾款支付结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="balanceDueEndTime">
                <a-date-picker placeholder="请选择尾款结束时间" :show-time="{ format: 'HH:mm' }" valueFormat="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm"
                  v-model="form.balanceDueEndTime" style="width: 40%" />
              </a-form-model-item>
            </a-col>

            <a-col :span="24">
              <a-form-model-item label="发货时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sendDate">
                <a-date-picker placeholder="请选择发货时间" :show-time="{ format: 'HH:mm' }" valueFormat="YYYY-MM-DD HH:mm:ss" format="YYYY-MM-DD HH:mm"
                  v-model="form.sendDate" style="width: 40%" />
              </a-form-model-item>
            </a-col>

            <!-- <a-col :span="24" v-if="!form.pid">
              <a-form-model-item label="竖向广告图" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="adImgUrl">
                <j-image-upload class="avatar-uploader" :accept="'image/png,image/jpeg'" text="上传" v-model="form.adImgUrl"></j-image-upload>
              </a-form-model-item>
            </a-col> -->

            <a-col :span="24">
              <a-form-model-item label="每人限制购买数量" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="userNum">
                <a-input-number v-model="form.userNum" placeholder="请输入每人限制购买数量,-1表示不限制" style="width: 40%" />
              </a-form-model-item>
            </a-col>

          </a-row>
        </a-card>
<!--        <a-card title="分销设置" :bordered="false">-->
<!--          <a-row>-->
<!--            <a-col :span="24">-->
<!--              <a-form-model-item label="是否参与分销" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isCommission">-->
<!--                <a-radio-group :disabled="good_lib_type==2" v-model="form.isCommission">-->
<!--                  <a-radio :value="0">否</a-radio>-->
<!--                  <a-radio :value="1">是</a-radio>-->
<!--                </a-radio-group>-->
<!--              </a-form-model-item>-->
<!--            </a-col>-->
<!--            <a-col :span="24">-->
<!--              <a-form-model-item label="分成比例(%)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="rate">-->
<!--                <a-input-number :disabled="good_lib_type==2" v-model="form.rate" :min="0" :step="1" placeholder="请输入分成比例(%)" style="width: 100%" />-->
<!--              </a-form-model-item>-->
<!--            </a-col>-->
<!--          </a-row>-->
<!--        </a-card>-->
      </a-form-model>
    </j-form-container>
    <gms-zy-good-ref ref="modalGoodsSet" @ok="modalGoodsOk" />
    <gms-good-lib-ref ref="modalGoodsLib" @ok="modalLibGoodsOk" />
  </a-spin>
</template>

<script>

import { httpAction, getAction } from '@/api/manage'
import pick from 'lodash.pick'
import { validateDuplicateValue } from '@/utils/util'
import JFormContainer from '@/components/jeecg/JFormContainer'
import JDate from '@/components/jeecg/JDate'
import GmsZyGoodRef from '@/views/gospel/mallBase/good/modules/GmsZyGoodRef'
import GmsGoodLibRef from '@/views/gospel/mallPlus/good/modules/GmsGoodLibRef'
import JImageUpload from '@/components/jeecg/JImageUpload'

export default {
  name: 'YymsGoodForm',
  components: {
    JFormContainer,
    JDate,
    JImageUpload,
    GmsZyGoodRef,
    GmsGoodLibRef
  },
  props: {
    //流程表单data
    formData: {
      type: Object,
      default: () => { },
      required: false
    },
    //表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data () {
    var validateStartTime = (rule, value, callback) => {
      console.log(value)
      if (!value) {
        callback(new Error('请选择定金开始时间'))
      } else if (this.form.endTime && (this.form.startTime >= this.form.endTime)) {
        callback(new Error('定金开始时间不得晚于定金结束时间'))
      } else {
        callback()
      }
    }
    var validateEndTime = (rule, value, callback) => {
      console.log(value)
      if (!value) {
        callback(new Error('请选择结束时间'))
      } else if (this.form.endTime && (this.form.startTime >= this.form.endTime)) {
        callback(new Error('定金结束时间不得早于定金开始时间'))
      } else {
        callback()
      }
    }
    var validateStart1Time = (rule, value, callback) => {
      console.log(value)
      if (!value) {
        callback(new Error('请选择尾款支付开始时间'))
      } else if (this.form.endTime && (this.form.balanceDueStartTime <= this.form.endTime)) {
        callback(new Error('尾款支付开始时间不得早于定金结束时间'))
      } else {
        callback()
      }
    }
    var validateEnd1Time = (rule, value, callback) => {
      console.log(value)
      if (!value) {
        callback(new Error('请选择尾款支付结束时间'))
      } else if (this.form.balanceDueStartTime && (this.form.balanceDueStartTime >= this.form.balanceDueEndTime)) {
        callback(new Error('尾款支付结束时间不得早于尾款支付开始时间'))
      } else {
        callback()
      }
    }
    var validateSendTime = (rule, value, callback) => {
      console.log(value)
      if (!value) {
        callback(new Error('请选择发货时间'))
      } else if (this.form.balanceDueStartTime && (this.form.balanceDueStartTime >= this.form.sendDate)) {
        callback(new Error('发货时间不得早于尾款支付开始时间'))
      } else {
        callback()
      }
    }
    return {
      good_lib_type: 1,//1：自营商品，2：活动商品库
      checkSkuVisible: false,
      checkedSkuAll: false,
      checkedSku1: false,
      checkedSku2: false,
      checkedValue1: 0,
      checkedValue2: 0,
      form: {
        shopId: '',
        supplierId: '',
        title: '',
        srcId: '',
        originalPrice: 0,
        price: 0,
        adImgUrl: '',
        isCommission: 0,
        rate: 0,
        skuList: [],
        startTime: '',
        endTime: '',
        balanceDueStartTime: '',
        balanceDueEndTime: '',
        canRefund: 1,
        sendDate: '',
        userNum: 1,
        deposit: '',
        libId: ''
      },
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      rules: {
        srcId: [
          { required: true, message: '请选择商品!' },
        ],
        price: [
          { required: true, message: '请输入价格!' },
        ],
        // adImgUrl: [
        //   { required: true, message: '请选择图片!' },
        // ],
        startTime: [
          { required: true, validator: validateStartTime, trigger: 'change' }
        ],
        endTime: [
          { required: true, validator: validateEndTime, trigger: 'change' }
        ],
        balanceDueStartTime: [
          { required: true, validator: validateStart1Time, trigger: 'change' },
        ],
        balanceDueEndTime: [
          { required: true, validator: validateEnd1Time, trigger: 'change' },
        ],
        sendDate: [
          { required: true, validator: validateSendTime, trigger: 'change' },
        ],
        deposit: [
          { required: true, message: '请输入定金!' },
        ],
      },
      url: {
        add: "/mallPlus/yymsGood/add",
        edit: "/mallPlus/yymsGood/edit",
        queryById: "/mallPlus/yymsGood/queryById"
      }
    }
  },
  computed: {
    formDisabled () {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    max_price: function () {
      let sum = 0
      for (let i = 0; i < this.form.skuList.length; i++) {
        if (sum == 0) {
          sum = this.form.skuList[i].yyPrice
        } else {
          if (this.form.skuList[i].yyPrice < sum) {
            sum = this.form.skuList[i].yyPrice
          }
        }

      }

      return sum - 0.01
    }
  },

  created () {

  },
  methods: {
    disabledStartDate (startValue) {
      const endValue = this.form.endTime

      if (!startValue) {
        return false
      } else {
        return startValue.valueOf() <= Date.now() - 86400000
      }

    },
    modalGoodsOk (row) {
      const self = this
      this.form.title = row.title
      this.form.shopId = row.shopId
      this.form.supplierId = row.supplierId
      this.form.srcId = row.id
      this.form.price = row.price
      this.form.originalPrice = row.originalPrice
      this.form.isCommission = row.isCommission
      this.form.rate = row.rate
      this.form.adImgUrl = row.imgUrl
      this.form.libId = null
      if (this.form.srcId) {
        this.getSrSkuList(this.form.srcId)
      }
    },
    modalLibGoodsOk (row) {
      const self = this
      this.form.title = row.title
      this.form.shopId = row.shopId
      this.form.supplierId = row.supplierId
      this.form.srcId = row.itemId
      this.form.price = row.price
      this.form.originalPrice = row.originalPrice
      this.form.isCommission = row.isCommission
      this.form.rate = row.rate
      this.form.adImgUrl = row.imgUrl
      this.form.libId = row.id
      if (this.form.srcId) {
        this.getSrSkuList(this.form.srcId)
      }
    },
    goodSelect () {
      let self = this
      if (self.good_lib_type == 1) {
        //自营
        self.$refs.modalGoodsSet.visible = true
        self.$refs.modalGoodsSet.open()
      } else {
        self.$refs.modalGoodsLib.visible = true
        self.$refs.modalGoodsLib.open(5)
      }

    },
    getSrSkuList (id) {
      let self = this
      getAction("/mallBase/gmsGood/querySkuById", { id: id }).then(res => {
        if (res.success) {
          if (res.result) {
            this.form['skuList'] = res.result
          } else {
            this.form['skuList'] = []
          }

        } else {
          this.$message.error(res.message)
        }
      })
    },
    add (good_lib_type) {
      this.good_lib_type = good_lib_type
      this.edit({
        shopId: '',
        supplierId: '',
        title: '',
        srcId: '',
        originalPrice: 0,
        price: 0,
        adImgUrl: '',
        isCommission: 0,
        rate: 0,
        skuList: [],
        startTime: '',
        endTime: '',
        balanceDueStartTime: '',
        balanceDueEndTime: '',
        canRefund: 1,
        sendDate: '',
        userNum: 1,
        deposit: '',
        libId: ''
      })
    },
    edit (record) {

      this.form = Object.assign({}, record)
      if (record.shopId) {
        if (record.shopId === "A00001A00001") {
          this.good_lib_type = 1
        } else {
          this.good_lib_type = 2
        }
      }
      this.visible = true
      if (this.form.srcId) {
        this.getSrSkuList(this.form.srcId)
      }
    },


    submitForm () {
      const that = this
      for (let i = 0; i < this.form.skuList.length; i++) {
        if (this.good_lib_type == 1 && !this.form.skuList[i].yyPrice) {
          that.$message.success("请先输入规格组活动价")
          return
        }
      }
      // 触发表单验证
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          if (!this.form.id) {
            httpurl += this.url.add
            method = 'post'
          } else {
            httpurl += this.url.edit
            method = 'put'
          }
          let formData = Object.assign({}, this.form)
          console.log("表单提交数据", formData)
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message)
              that.$emit('ok')
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }

      })
    },
    popupCallback (row) {
      this.form = row
    },

    setCheckedSkuAll () {
      if (this.checkedSkuAll) {
        this.checkedSku1 = true
        this.checkedSku2 = true
      } else {
        this.checkedSku1 = false
        this.checkedSku2 = false
      }
    },
    setAllSkuClear () {
      this.checkedValue1 = 0
      this.checkedValue2 = 0
    },
    deleteItem2 (index) {
      this.form.skuList[index].msStock = 0
    },
    deleteItem3 (index) {
      this.form.skuList[index].ptStock = 0
    },
    deleteItem5 (index) {
      this.form.skuList[index].yyStock = 0
    },
    setAllSku () {
      for (let i = 0; i < this.form.skuList.length; i++) {
        if (this.checkedSku1) {
          this.form.skuList[i].yyPrice = this.checkedValue1
        }
        if (this.checkedSku2) {
          this.form.skuList[i].yyStock = this.checkedValue2
        }

      }
      this.checkSkuVisible = false
    },
  }
}
</script>
<style lang="less" scoped>
.sku-panel {
  width: 100%;
  padding: 15px;
  box-sizing: border-box;
  border: solid 1px #e9e9e9;
  .sku-set-item {
    padding-bottom: 15px;
    .sku-set-name {
      display: flex;
      padding: 5px;
      background-color: #f4f4f4;
    }
    .sku-set-name-label {
      width: 100px;
      text-align: right;
    }
    .sku-set-value {
      padding: 12px 5px;
      display: flex;
      .sku-sub-items {
        display: block;
        flex: 1;
        .sku-sub-item {
          // display: inline-block;displaydisplay
          float: left;
          padding-bottom: 5px;
          .sku-sub-item-box {
            position: relative;
            .sku-sub-item-del {
              display: none;
              font-size: 20px;
              position: absolute;
              color: red;
              cursor: pointer;
              top: -10px;
              right: -10px;
            }
          }
          .sku-sub-item-box:hover {
            .sku-sub-item-del {
              display: block;
            }
          }
        }
        .mr-5 {
          margin-right: 10px;
        }
      }
    }
  }
  .sku-list {
    .sku-list-row {
      display: flex;
      border-bottom: solid 1px #e9e9e9;
      line-height: 36px;
      .sku-list-col {
        padding: 2px;
        line-height: 36px;
        color: #777777;
        width: 112px;
      }
      .w-150 {
        width: 150px;
      }
      .w-80 {
        width: 105px;
        input {
          padding-left: 2px;
          padding-right: 2px;
        }
      }
      .flex-2 {
        flex: 1;
      }
      .row-head {
        color: #333;
        font-weight: 600;
      }
    }
    .sku-list-setting {
      display: flex;
      line-height: 36px;
      .setting-item {
        padding-right: 8px;
      }
    }
  }
}
.popover-panel {
  padding: 5px;
  box-sizing: border-box;
  .popover-panel-row {
    // display: flex;displaydisplay
    margin-bottom: 5px;
    line-height: 36px;
    .w-150 {
      width: 100px;
      display: inline-block;
    }
    .pp-f-1 {
      display: inline-block;
      width: 139px;
    }
    .mr-10 {
      margin-right: 0px;
    }
  }
}
.is-not-null:before {
  content: '*';
  color: #ff4949;
  margin-right: 4px;
}
.classBox {
  width: 100%;
  height: 100px;
  display: flex;
  align-items: center;
  font-size: 14px;
  color: #666666;
  padding: 0 43px;
  box-sizing: border-box;
  .classBox-i {
    color: #ff4949;
    margin-right: 3px;
  }
}
</style>
